package com.kunbo.cn.service.impl.system;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import com.kunbo.cn.dao.system.DepartDao;
import com.kunbo.cn.entity.system.Depart;
import com.kunbo.cn.service.system.DepartService;
import com.kunbo.cn.util.tree.TreeUtil;
@Service
public class DepartServiceImpl implements DepartService {
	@Autowired
	private DepartDao departDao;

	@Override
	public void save(Depart depart) {
		departDao.save(depart);
	}

	@Override
	public void update(Depart depart) {
		departDao.save(depart);
	}

	@Override
	public void delete(String id) {
		// TODO Auto-generated method stub
		departDao.delete(id);
	}

	@Override
	public Depart findById(String id) {
		// TODO Auto-generated method stub
		return departDao.findOne(id);
	}

	@Override
	public List<Depart> getDepartTreeList() {
		List<Depart> list = (List<Depart>) departDao.findAll();
		List data = new TreeUtil().data(list);
		return data;
	}

	@Override
	public Page<Depart> findDepartByName(String name, Integer pageNo, Integer pageSize) {
		Pageable pageable = new PageRequest(pageNo-1, pageSize);
        Specification<Depart> confusion=new Specification<Depart>() {
            @Override
            public Predicate toPredicate(Root<Depart> root, CriteriaQuery<?> query,
                    CriteriaBuilder criteriaBuilder) {
            	List<Predicate> predicates = new ArrayList<>();
            	if(!"".equals(name)) {
            		predicates.add(criteriaBuilder.like(root.get("name"), "%"+name+"%"));
            	}
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        return departDao.findAll(confusion, pageable);
		
	}

}
